import csv
import os
import time

#控制类
class Controller:

    def __init__(self,count,packageName):
        self.counter=count
        self.alldata=[('timestamp','cpustatus')]
        self.packageName=packageName

    #单次执行过程
    def testprocess(self):
        result=os.popen('adb shell dumpsys cpuinfo |grep %s'%self.packageName)
        # print(result.read(),type(result.read()))
        for line in result.readlines():
            cpuvalue = line.split("%")[0]
            currenttime=self.getCurrentTime()
            self.alldata.append((currenttime,cpuvalue))

    #多次执行过程
    def run(self):
        while self.counter>0:
            self.testprocess()
            self.counter-=1
            time.sleep(5) #5秒采集一次数据

    #获取当前的时间戳
    def getCurrentTime(self):
        currentTime=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
        return currentTime

    #数据存储
    def SaveDatatoCSV(self):
        with open('cpustatus.csv','w+') as fp:
            write=csv.writer(fp)
            write.writerows(self.alldata)

if __name__ == '__main__':
    controller=Controller(10,packageName='com.estrongs.android.pop')
    controller.run()
    controller.SaveDatatoCSV()